package edu.umassd.raddacl.parsing;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import edu.umassd.raddacl.DataSet;
import edu.umassd.raddacl.util.Locations;

/**
 * Creates a matrix out of a single file located on the system.
 * 
 * @author Dan Avila
 * 
 */
@Component
public class FileSystemLoader implements DataSetLoader
{
	@Autowired
	private DataSet dataset;

	@Autowired
	private Locations locations;

	@Value("${current.dataset.name}")
	private String dataSetName;

	private Path location;

	private Pattern regex = Pattern.compile("(\\d{1,}[.]?\\d{0,})");
	private Pattern newLine = Pattern.compile("\\r\\n");

	private int attributeCount;
	private int vectorCount;

	@PostConstruct
	protected void setInitialPath()
	{
		locations.changeDataSet(dataSetName);

		this.location = locations.getInputFile();
	}

	/**
	 * Loads the data set from a file. The format of the file should be rows of
	 * values.
	 */
	@Override
	public DataSet load()
	{
		if (location == null)
		{
			throw new IllegalArgumentException("setLocation() cannot be null.");
		}

		double[][] data = null;

		try
		{
			String fileContents = new String(Files.readAllBytes(location));

			if (fileContents.trim().equals(""))
			{
				throw new IllegalStateException("File is empty.");
			}

			calculateVectorCount(fileContents);
			calculateAttributeCount(fileContents);

			data = new double[vectorCount][attributeCount];

			Matcher matcher = regex.matcher(fileContents);

			for (int i = 0; i < vectorCount; i++)
			{
				for (int x = 0; x < attributeCount; x++)
				{
					matcher.find();

					double attributeValue = Double.valueOf(matcher.group(1));

					data[i][x] = attributeValue;
				}
			}
		}
		catch (IOException e)
		{
			throw new IllegalStateException(e);
		}

		dataset.set(data);

		return dataset;
	}

	/**
	 * Counts the number of attributes in the first vector.
	 * 
	 * @param fileContents
	 *            - the data set file contents.
	 */
	private void calculateAttributeCount(String fileContents)
	{
		Matcher newLine = this.newLine.matcher(fileContents);

		int index = fileContents.length();

		if (newLine.find())
		{
			index = newLine.start();
		}

		String firstVector = fileContents;

		if (index != -1)
		{
			firstVector = fileContents.substring(0, index);
		}

		Matcher matcher = regex.matcher(firstVector);

		attributeCount = 0;

		while (matcher.find())
		{
			attributeCount++;
		}
	}

	/**
	 * Calculates the number of attributes in the first vector. This value will
	 * be used for memory allocation and parsing assumptions.
	 * 
	 * @param fileContents
	 *            - the data set file contents.
	 */
	private void calculateVectorCount(String fileContents)
	{
		Matcher matcher = newLine.matcher(fileContents);

		vectorCount = 0;

		while (matcher.find())
		{
			vectorCount++;
		}

		vectorCount++;
	}

	/**
	 * Changes the location of the resource we are using to load data from.
	 * 
	 * @param location
	 *            - the location of the data set file..
	 */
	public void setLocation(Path location)
	{
		this.location = location;
	}

	/**
	 * The current location this loader is using. Default value is null.
	 * 
	 * @return a {@link Path} representing the file we are loading.
	 */
	public Path getLocation()
	{
		return location;
	}
}
